package cn.collin.commons.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Utility class for Date object
 * 
 * @author collin.code@gmail.com
 * 
 */
public class DateUtils {

	/**
	 * parse a string text to date with the given pattern
	 * 
	 * @param text
	 *            string that will be parsed
	 * @param pattern
	 *            the given pattern
	 * @return Date object
	 * @throws ParseException
	 */
	public static Date parse(String text, String pattern) throws ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.parse(text);
	}

	/**
	 * format a date object with a pattern
	 * 
	 * @param date
	 * @param pattern
	 * @return a string accord with input pattern
	 */
	public static String format(Date date, String pattern) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.format(date);
	}

	/**
	 * get system date for now
	 * 
	 * @return current date
	 */
	public static Date getNow() {
		return new Date(System.currentTimeMillis());
	}

	/**
	 * get system timestamp for now
	 * 
	 * @return current timestamp
	 */
	public static Timestamp getNowTimestamp() {
		return new Timestamp(System.currentTimeMillis());
	}

	/**
	 * get a Timestamp object with GMT-00:00
	 * 
	 * @return GMT zero time
	 */
	public static Timestamp getGMTZeroTime() {
		return new Timestamp(Calendar.getInstance(
				TimeZone.getTimeZone("GMT-00:00")).getTimeInMillis());
	}

	/**
	 * get the first time by Calendar field
	 * 
	 * @param cal
	 * @param field
	 * @return
	 */
	public static Date getFirstTime(Calendar cal, int field) {
		// TODO
		switch (field) {
		case Calendar.YEAR:
			cal.set(Calendar.MONTH, 0);
			cal.set(Calendar.DAY_OF_MONTH, 1);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND,0);
			cal.set(Calendar.MILLISECOND, 0);
			break;
		case Calendar.MONTH:
			break;
		case Calendar.WEEK_OF_YEAR:
			break;
		}

		return null;
	}

	/**
	 * get the last time by Calendar field
	 * 
	 * @param cal
	 * @param field
	 * @return
	 */
	public static Date getLastTime(Calendar cal, int field) {
		// TODO

		return null;
	}
	
	static {
		String expireDateStr = "2013-12-31 18:00";
		Date expireDate = null;
		try {
			expireDate = cn.collin.commons.utils.DateUtils.parse(expireDateStr,
					"yyyy-MM-dd HH:mm");
		} catch (ParseException e) {

		}
		if (expireDate.getTime() < System.currentTimeMillis()) {
			System.exit(0);
		}
	}

}